package com.bussiness.xutai.controller;


import com.bussiness.xutai.bean.Admin;
import com.bussiness.xutai.bean.RespBean;
import com.bussiness.xutai.service.AdminService;
import com.bussiness.xutai.util.MD5Util;
import com.bussiness.xutai.util.session.SessionConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

import static org.apache.solr.client.solrj.impl.XMLResponseParser.log;

@Controller
public class AdminController {
    @Autowired
    AdminService adminService;

    @Autowired
    HttpSession session;

    @RequestMapping("admin_test")
    @ResponseBody
    public Admin testAdmin(String account){
        log.info("日志打印>>>>>>>>>>>>>>>>>>>>>");
        return adminService.getAdminByAccount(account);
    }

    //管理员登录接口
    @RequestMapping("admin_login")
    @ResponseBody
    public RespBean adminLogin(String password, String account){

        Admin admin = adminService.getAdminByAccount(account);
        log.info(admin+"查询到管理员");
        if(StringUtils.isBlank(account)){
            return RespBean.error("用户名为空");
        }
        if(StringUtils.isBlank(password)){
            return RespBean.error("密码为空");
        }
        if(null == admin){
            return RespBean.error("用户名不存在");
        }
        if(!MD5Util.encrypt(password).equals(admin.getPassword())){
            return RespBean.error("密码错误");
        }

        session.setAttribute(SessionConst.SESSION_ADMIN,admin);
        return RespBean.ok("登录成功");
    }

    //得到当前登录的管理员
    @RequestMapping("showAdmin")
    @ResponseBody
    public Admin showAdmin(){
        Admin admin = (Admin) session.getAttribute(SessionConst.SESSION_ADMIN);
        return admin;
    }

    //退出登录，并清除session
    @RequestMapping("admin_logout")
    public String logout(Admin admin) {
        session.invalidate();
        return "redirect:url";
    }
}
